#coding:utf-8
from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

from django.conf import settings
import MySQLdb
import json
from aliexpress.api import datelist
import datetime,time
import random
import urllib
import requests
import hashlib
from API import *
from aliexpress.models import Country,TranslateContent,ProductDeclare,StoreInfo,\
    OrderMemo,OrderDealMark,DeliveryInformation,ChooseLogistics,OrderDeal
from aliexpress.views import countryTanslate

from django.views.decorators.csrf import csrf_exempt

from django.conf import settings
from .basecon import *
from erp.models import *
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )


def productStockList(request):
    if not request.user.is_authenticated():
        return redirect('/ucenter/login/'+"?from="+request.get_full_path())
    user = request.user

    #获取用户授权查看的店铺
    sql = 'SELECT `store_id` from `sys_store_user` WHERE `user_id`="%d"'%(user.id)
    userStores = my_custom_sql(sql)

    page = request.GET.get('page','1')
    searchTxt = request.GET.get('searchTxt',None)
    searchType = request.GET.get('searchType',None)

    print 2
    if len(userStores)>0:

        sql = 'SELECT A.ID,A.sku,GROUP_CONCAT(B.skuImage) as image,c.chinese_name,status,unSendCount,category,sellCount1,sellCount2,sellCount3,weight,currencyCode,realStock,storage_num from sys_product_sku as A LEFT JOIN sys_product_sku_property as B on A.ID = B.sysSkuId LEFT JOIN sys_product as C on A.productId = C.ID where 1=1 '
        sql += ' and A.CREATE_USER_ID = %d '%(user.id)
        sql1='SELECT count(*) as sum from (SELECT A.ID from sys_product_sku as A LEFT JOIN sys_product_sku_property as B on A.ID = B.sysSkuId LEFT JOIN sys_product as C on A.productId = C.ID where 1=1  '
        sql1 += ' and A.CREATE_USER_ID = %d ' % (user.id)
        print  sql
        if searchTxt:
            word = searchTxt.strip()
            word = word.replace('"','\\"')
            sql += 'AND ( A.sku like "%'+word+'%" or chinese_name like "%'+word+'%")'
            sql1 += 'AND ( A.sku like "%' + word + '%" or chinese_name like "%' + word + '%")'
        pageSize = 30
        sql+='GROUP BY A.ID  order by ID desc '
        sql1 += 'GROUP BY A.ID ) as AA '
        sql+=' limit '+str((int(page)-1)*int(pageSize))+','+str(int(page)*int(pageSize))
        print(sql)
        temp = my_custom_sql(sql)
        print temp
        totalCount = my_custom_sql(sql1)[0]["sum"]

        for pro in temp:
            images = pro["image"]
            image = images.split(',',1)[0]
            pro["image"] = image
        productData = temp
        currentPage = int(page)

        mod = divmod(int(totalCount),pageSize)

        if mod[1]>0:
            totalPage = mod[0]+1
        else:
            totalPage = mod[0]

        pageList = range(1,totalPage+1)

        pageData = []

        for pg in pageList:
            if currentPage == pg:
                active = True
            else:
                active = False
            pageData.append({"page":pg,"active":active})
    else:
        msg = '您没有被授权查看店铺的产品'
        return render(request,'aside/error.html',locals())
    return render(request, 'aside/erp/sysproductstock.html', locals())

#编辑在线库存
def editProductStock(request):
    id = request.GET.get('id',None)
    print id
    stock = request.GET.get('stock',None)
    sku = ProductSKU.objects.using('erp').get(id=id)
    sku.realStock = stock
    sku.save()
    data = {"status": 1}
    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type='application/json; charset=utf-8')

#添加采购记录
def addPurchase(request):
    skuId = request.GET.get('id',None)
    qty = request.GET.get('qty',None)
    totalPrice = request.GET.get('totalPrice',None)
    note = request.GET.get('note',None)
    #跟新库存
    stock = request.GET.get('stock', None)
    sku = ProductSKU.objects.using('erp').get(id=id)
    sku.realStock = stock + sku.realStock
    sku.save()
    #添加采购记录
    purchase = Purchase

def getProductDetail(request):
    productId = request.GET.get('productId',None)
    sql = 'SELECT * FROM `e_productlibrary` where ID = '+productId
    print sql
    temp = my_custom_sql(sql)
    return HttpResponse(json.dumps(temp[0],ensure_ascii=False),content_type='application/json; charset=utf-8')




def editProductLibrary(request):
    user = request.user
    productId = request.GET.get('productId', None)
    NUMBERS = request.GET.get("NUMBERS",None)
    print NUMBERS+"*****"
    NAME = request.GET.get('NAME', None)
    CHANGJIANAME = request.GET.get('CHANGJIANAME', None)
    CHANGJIAURL = request.GET.get('CHANGJIAURL', None)
    NOTE = request.GET.get('NOTE', None)
    #修改逻辑
    if productId and productId != '0':

        data = {"status":1}
        return HttpResponse(json.dumps(data, ensure_ascii=False), content_type='application/json; charset=utf-8')


def delProductLibrary(request):
    productId = request.GET.get('productId', None)
    Productlibrary.objects.using('erp').filter(ID=productId).delete()
    data = {"status": 1}
    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type='application/json; charset=utf-8')